#!/usr/bin/python3
# ******************************************************************************
# Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved.
# licensed under the Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#     http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
# PURPOSE.
# See the Mulan PSL v2 for more details.
# ******************************************************************************/
import os.path
import xml.etree.ElementTree as ET
import csv

current_path = os.path.relpath(os.path.dirname(__file__))
header = ['name', 'group']
"""
使用方法：
1、将解压后的xml文件放到同目录的data，（支持多个）
2、执行该文件，python3 package_group.py
3、生成的csv文件在该目录下，以xml文件命名（后缀改为了.csv）。
"""


def parse_xml(xml_path=None):
    """
    解析xml
    :param xml_path: xml文件路径
    :return: 解析内容
    """
    xml_path = os.path.join(current_path, "xml_data") if xml_path is None else xml_path
    namespace = {"xmlns": "http://linux.duke.edu/metadata/common", "xmlns_rpm": "http://linux.duke.edu/metadata/rpm"}
    for xml_file in os.listdir(xml_path):
        name_group_list = []
        xml_real_file = os.path.join(xml_path, xml_file)
        # xml_real_file = os.path.join(xml_path, "test.xml")
        tree = ET.parse(xml_real_file)
        root = tree.getroot()
        for package in root.findall("xmlns:package", namespace):
            package_name = package.find("xmlns:name", namespace)
            package_group = package.find("xmlns:format//xmlns_rpm:group", namespace)
            name_group_list.append({"name": package_name.text, "group": package_group.text})

        write_to_csv(data=name_group_list, csv_path=str(xml_file).replace("xml", 'csv'))


def write_to_csv(data, csv_path=None):
    """
    将数据写入csv
    :param data: 写入的数据
    :param csv_path: csv的路径
    :return: csv文件
    """
    csv_path = os.path.join(current_path, "package_group.csv") if csv_path is None else csv_path
    with open(csv_path, 'w') as csv_file:
        csv_writer = csv.DictWriter(csv_file, header)
        csv_writer.writeheader()
        csv_writer.writerows(data)


if __name__ == '__main__':
    parse_xml()
